<script setup>
import { ref, computed } from 'vue'
import store from '@/store'
import NoticeModal from './NoticeModal.vue'
import { useButtonStyle } from '@/composables/useButtonStyle.js'
// 正确使用组合式函数获取按钮样式
const buttonStyle = useButtonStyle()

const props = defineProps({
  orderList: {
    type: Array,
    default: () => [],
  },
  loadStatus: {
    type: String,
    default: "loadmore"
  },
  type: {
    type: String,
    required: true
  }
})
const isExternal = computed(() => store.state.isExternal)
const emit = defineEmits(['clickDelete', 'clickEdit', "clickGoods", "clickBtn"])

const clickGoods = (item) => {
  emit('clickGoods', item)
}
const clickConfirmGoods = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/orderManagement/receiptConfirmation?data=${data}&type=${props.type}`
  })
}
const clickLog = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/orderManagement/operationLog?data=${data}&type=${props.type}`
  })
}

const activeIndex = ref(null)
// 存储每个菜单项的显示方向
const isMenuAbove = ref({})
// 预估菜单高度
const menuHeight = 360
// 屏幕下半部分的阈值
const screenBottomThreshold = 0.6

const toggleMenu = (e, index) => {
  // 如果是关闭菜单，直接返回
  if (activeIndex.value === index) {
    activeIndex.value = null
    return
  }

  try {
    // 获取系统信息
    const { windowHeight } = uni.getSystemInfoSync()
    // 计算屏幕30%位置的阈值
    const threshold = windowHeight * 0.7

    // 获取点击事件的y坐标
    let clickY = 0
    if (e && e.touches && e.touches[0]) {
      clickY = e.touches[0].clientY
    } else if (e && e.clientY) {
      clickY = e.clientY
    }

    // 判断点击位置：如果在屏幕下方30%区域，菜单向上显示
    isMenuAbove.value[index] = clickY > threshold
  } catch (error) {
    console.log('获取点击位置失败，使用基于索引的默认判断', error)
    // 失败时使用基于索引的回退方案
    isMenuAbove.value[index] = index > props.orderList.length * 0.7
  }

  // 打开菜单
  activeIndex.value = index
}

const closeMenu = () => {
  activeIndex.value = null
}

/**
 * 
 * @param {Object} val 当前数据项
 * @param {*} type 操作类型 入库:2收货检查 3收货确认 4入库确认 出库：2货物抽检 3提货核对 4出库确认
 * 
 */
const changeBtn = (val, type) => {
  const data = JSON.stringify(val)
  uni.navigateTo({
    url: `/pages/orderManagement/receiptConfirmation?data=${data}&type=${props.type}&confirmType=${type}`
  })
  closeMenu()
}

const NoticeModalRef = ref(null)
/**
 * 
 * @param {Object} val 当前数据项
 * @param { String } type 1 入库通知 2 出库通知
 */
const changeShippingNotice = (val, type) => {
  NoticeModalRef.value.open(val, type)
  closeMenu()
}

const clickScore = item => {
  uni.navigateTo({
    url: `/pages/consult/scoreForm?orderId=${item.id}`
  })
}
</script>


<template>
  <view class="reservation-list-container">
    <view v-if="orderList.length">
      <view class="list-card" v-for="(item, index) in orderList" :key="item.id">
        <view class="card-header">
          <view class="order-info">
            <text class="order-id">订单ID：{{ item.currentId }}</text>
            <text class="status-btn">{{ item.statusStr }}</text>
          </view>
        </view>
        <view class="card-content">
          <view class="info-grid">
            <view class="info-item full-width">
              <text class="info-label">客户</text>
              <text class="info-value">{{ item.company }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">建单日期</text>
              <text class="info-value">{{ item.createdate }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">月台</text>
              <text class="info-value">{{ item.platformnum }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">车辆</text>
              <text class="info-value">{{ item.carStr }}</text>
            </view>
            <view class="info-item ">
              <text class="info-label">预计到达时间</text>
              <text class="info-value">{{ item.expectdate }}</text>
            </view>
          </view>
        </view>
        <!-- 按钮操作 -->
        <view class="card-actions">
          <u-button size="mini" :custom-style="buttonStyle.customStyle" type="primary" plain @click="clickScore(item)">
            评价
          </u-button>
          <u-button size="mini" :custom-style="buttonStyle.customStyle" type="primary" plain @click="clickGoods(item)">
            详情
          </u-button>
          <u-button size="mini" :custom-style="buttonStyle.customStyle" type="primary" plain @click="clickLog(item)">
            操作日志
          </u-button>
          <u-button v-if="isExternal" size="mini" :custom-style="buttonStyle.customStyle" type="primary" plain
            @click="clickConfirmGoods(item)">
            {{ type === 'inorder' ? '收货确认' : '提货核对' }}
          </u-button>
          <view class="action-buttons" v-else>
            <u-button size="mini" :custom-style="buttonStyle.customStyle" type="primary" plain
              @click.stop="toggleMenu($event, index)" :id="`menu-btn-${index}`">
              更多
            </u-button>
            <!-- 使用条件渲染而非动画过渡，避免闪烁问题 -->
            <view class="overlay" v-if="activeIndex === index" @tap="activeIndex = null" @touchmove.stop></view>
            <view v-if="activeIndex === index" :class="['btn-content', (isMenuAbove[index] === true) ? 'above' : '']"
              @click.stop>
              <!-- 入库 -->
              <view v-if="type === 'inorder'">
                <view class="action-btn flex" @click="changeBtn(item, '2')">
                  <text class="btn-icon">📦</text>
                  <text class="btn-text">收货检查</text>
                </view>
                <view class="action-btn flex" @click="changeBtn(item, '3')">
                  <text class="btn-icon">📋</text>
                  <text class="btn-text">收货确认</text>
                </view>
                <view class="action-btn flex" @click="changeBtn(item, '4')">
                  <text class="btn-icon">🏠</text>
                  <text class="btn-text">入库确认</text>
                </view>
                <view class="action-btn flex" @click="changeShippingNotice(item, '1')">
                  <text class="btn-icon">💬</text>
                  <text class="btn-text">入库通知</text>
                </view>
              </view>
              <!-- 出库 -->
              <view v-else>
                <view class="action-btn flex" @click="changeBtn(item, '2')">
                  <text class="btn-icon">🔍</text>
                  <text class="btn-text">货物抽检</text>
                </view>
                <view class="action-btn flex" @click="changeBtn(item, '3')">
                  <text class="btn-icon">📋️</text>
                  <text class="btn-text">提货核对</text>
                </view>
                <view class="action-btn flex" @click="changeBtn(item, '4')">
                  <text class="btn-icon">🔓</text>
                  <text class="btn-text">出库确认</text>
                </view>
                <view class="action-btn flex" @click="changeShippingNotice(item, '3')">
                  <text class="btn-icon">💬</text>
                  <text class="btn-text">出库通知</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <u-loadmore :status="loadStatus" />
    </view>
    <view v-else>
      <u-empty mode="list"></u-empty>
    </view>
  </view>
  <NoticeModal ref="NoticeModalRef" />
</template>

<style lang="scss" scoped>
.reservation-list-container {
  width: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 98;
  background: transparent;
  /* 确保覆盖层响应点击事件 */
  pointer-events: auto;
}

.btn-content {
  position: absolute !important;
  top: calc(100% + 10rpx) !important;
  right: 0 !important;
  width: 240rpx !important;
  background: #ffffff !important;
  border-radius: 12rpx !important;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.12) !important;
  z-index: 999999 !important;
  padding: 16rpx 0 !important;
  overflow: visible !important;
  border: 1rpx solid #ddd !important;
  /* 确保渲染稳定性 */
  will-change: transform;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  /* 修复移动端渲染问题 */
  transform: translateZ(0);
  -webkit-transform: translateZ(0);

  &.above {
    top: auto !important;
    bottom: calc(100% + 10rpx) !important;
  }

  .action-btn {
    padding: 20rpx 24rpx !important;
    display: flex !important;
    align-items: center !important;
    transition: all 0.2s !important;
    background: #ffffff !important;

    .btn-icon {
      margin-right: 12rpx !important;
      font-size: 32rpx !important;
      font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif !important;
    }

    .btn-text {
      font-size: 28rpx !important;
      white-space: nowrap !important;
      color: #333 !important;
    }
  }
}

.list-card {
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-top: 20rpx;
  overflow: hidden;
  border: 1rpx solid #eee;
  position: relative;
}

.card-header {
  padding: 24rpx 24rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .order-id {
      font-size: $list-font-size;
      font-weight: 500;
      color: $list-color;
    }

    .status-btn {
      font-size: 28rpx;
      padding: 6rpx 16rpx;
      border-radius: 20rpx;
      background: #f6ffed;
      color: #52c41a;
      border: 1rpx solid #b7eb8f;
    }
  }
}

.card-content {
  padding: 20rpx 24rpx;
}

.info-grid {
  display: flex;
  flex-wrap: wrap;
  margin: -8rpx;
}

.info-item {
  width: 50%;
  padding: 8rpx;
  display: flex;
  flex-direction: column;

  &.full-width {
    width: 100%;
  }

  .info-label {
    font-size: $list-font-size;
    color: $list-color;
    margin-bottom: 4rpx;
  }

  .info-value {
    font-size: $list-font-size;
    color: $list-color;
    font-weight: 400;
  }
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  padding: 16rpx 24rpx;
  border-top: 1rpx solid #f0f0f0;
  gap: 16rpx;
}

.action-buttons {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

/* 确保菜单中的按钮不会被全局样式影响 */
.btn-content .action-btn {
  padding: 20rpx 24rpx !important;
  border-radius: 0 !important;
  background: #ffffff !important;
  border: none !important;
  width: 100% !important;
  box-sizing: border-box !important;
  display: flex !important;
  align-items: center !important;
}

/* 覆盖任何可能的全局样式 */
.list-card {
  overflow: visible !important;
}

.card-actions {
  overflow: visible !important;
}
</style>
